# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  include ExceptionNotifiable
  include Jqgrid

  #Funcionalidad para Popups
  include FormHelper
  layout :select_layout

  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  filter_parameter_logging :password
  helper_method :current_user, :lugar_actual, :current_modulos, :current_modulos_principales, :current_user_permissions, :acciones_controladas,:permissions_to_route?
  before_filter :log_all
  before_filter :require_login
  before_filter :check_permisos
  def initialize
    @perfiles = []
  end

  def lugar_actual
    "#{controller_name}: #{action_name}"
  end

  def cuenta(user)
    #preguntar si puede ver el show de usuarios
    permissions_to_route?('usuarios', 'show') ? user : {:controller => :usuarios, :action => :micuenta}
  end

  def permissions_to_route?(controller,accion)
    return true unless acciones_controladas[controller].try(:include?,accion) ? true : false
    current_user_permissions(current_user).nil? ? true : current_user_permissions(current_user)[controller].try(:include?,accion)
  end
  
  private
  def log_all
    session[:acciones_controladas]=nil
    session[:current_user_permissions]=nil
    session[:current_modulos_principales]=nil
    log = Log.new
    log.usuario = current_user
    log.accion = Accion.find_by_controller_nombre(controller_name).find_by_nombre(action_name)
    log.params = params.inspect
    log.ip = request.remote_ip
    log.save
  end

  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = SesionUsuario.find
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
    session[:acciones_controladas]=acciones_controladas
    session[:current_user_permissions]=current_user_permissions(@current_user)
    session[:current_modulos_principales]=current_modulos_principales
    @current_user
  end

  def current_user_permissions(current_user)
    return session[:current_user_permissions] if session[:current_user_permissions]
    return nil if current_user.nil?
    @current_user_permissions={}
    accion_ids=Accion.find(:all,:select=>"distinct accion_id",:joins=>[:perfiles],:conditions=>["permisos.perfil_id in (?)",current_user.perfil_ids]).collect{|a| a.accion_id}
    acciones=Accion.find(:all,
      :joins=>:controller,
      :select=>"acciones.nombre, controlleres.nombre as controller_nombre",
      :conditions=>"acciones.id IN (#{accion_ids.join(",")})")
    acciones.each do |accion|
      @current_user_permissions[accion.controller_nombre]||=[]
      next if @current_user_permissions[accion.controller_nombre].try(:include?,accion.nombre)
      @current_user_permissions[accion.controller_nombre]<<accion.nombre
    end
    @current_user_permissions
  end

  def acciones_controladas
    return session[:acciones_controladas] if session[:acciones_controladas]
    @acciones_controladas={}
    Accion.find(:all,
      :joins=>:controller,
      :select=>"acciones.nombre, controlleres.nombre as controller_nombre").each do |a|
      @acciones_controladas[a.controller_nombre]||=[]
      next if @acciones_controladas[a.controller_nombre].include?(a.nombre)
      @acciones_controladas[a.controller_nombre]<<a.nombre
    end
    @acciones_controladas
  end

  def current_modulos_principales
    return session[:current_modulos_principales] if (session[:current_modulos_principales] or current_user.nil?)
    @current_modulos_principales=current_user.modulos_principales.sort { |m1,m2| m1.orden<=>m2.orden }
    @current_modulos_principales.uniq!
    @current_modulos_principales
  end

  def require_login
    if !current_user
      session[:requested_url] = params
      flash[:notice] = "Debe iniciar sesi&oacute;n"
      redirect_to login_path
    end
  end
  #Verifique que los permisos del usuario contra los permisos que requiere el controller

  def check_permisos
    if !permissions_to_route?(controller_name, action_name)
      flash[:notice] = "No tiene permisos para acceder a este recurso"
      redirect_to denegado_path
    end
  end
end
